package demo.Socket.Talking;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/20-08-20-15:00
 * @Description：demo.Socket.Talking
 */
public class talking_server {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket accept = null;
        try {
            server= new ServerSocket(6677);
            while (true){
                accept = server.accept();
                new myThread(accept).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
class myThread extends Thread{
    static ArrayList<Socket> list = new ArrayList<>();
    private Socket accept = null;

    public myThread(Socket accept) {
        this.accept = accept;
        list.add(accept);
    }

    @Override
    public void run() {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            while(true){
                String s = null;

                reader= new BufferedReader(new InputStreamReader(accept.getInputStream()));

                s = reader.readLine();
                System.out.println(s);
                for (Socket socket : list) {
                    if(socket != accept){
                        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        writer.write(s);
                        writer.newLine();
                        writer.flush();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader != null){
                    reader.close();
                }
                if(writer!= null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
